import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:meco/common/index.dart';
import 'dart:io';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:meco/views/me/me/controller.dart';

class InformationController extends GetxController {
  InformationController();

  // 用户仓库
  final UserRepository _userRepository = UserRepository();

  // 用户服务
  final UserService _userService = Get.find<UserService>();

  // 当前用户
  final Rx<User?> currentUser = Rx<User?>(null);

  // 用户昵称控制器
  late TextEditingController nicknameController;

  // 选择的新头像文件
  final Rx<File?> selectedAvatar = Rx<File?>(null);

  // 初始化数据
  _initData() {
    // 获取当前登录用户
    currentUser.value = _userService.currentUser.value;

    // 初始化昵称输入框
    if (currentUser.value != null) {
      nicknameController.text =
          currentUser.value!.nickname ?? currentUser.value!.username;
    }

    update(["information"]);
  }

  // 选择头像
  Future<void> pickAvatar() async {
    try {
      final ImagePicker picker = ImagePicker();
      final XFile? image = await picker.pickImage(source: ImageSource.gallery);

      if (image != null) {
        selectedAvatar.value = File(image.path);
        update(["information"]);
      }
    } catch (e) {
      print('选择头像失败: $e');
      Get.snackbar(
        'Select avatar failed',
        'Failed to select image, please try again',
        snackPosition: SnackPosition.BOTTOM,
      );
    }
  }

  // 保存用户信息
  Future<void> saveUserInfo() async {
    if (currentUser.value == null) return;

    try {
      // 显示加载中
      EasyLoading.show(status: 'Saving...');

      // 更新昵称
      String newNickname = nicknameController.text.trim();
      if (newNickname.isEmpty) {
        newNickname = currentUser.value!.username;
      }

      // 更新头像路径 (在实际应用中，通常应该先上传图片到服务器，然后保存URL)
      String? newAvatar;
      if (selectedAvatar.value != null) {
        // 这里假设我们将文件保存在本地并使用路径
        // 在真实应用中应该上传到服务器并获取URL
        newAvatar = selectedAvatar.value!.path;
      }

      // 创建更新后的用户对象
      final updatedUser = currentUser.value!.copyWith(
        nickname: newNickname,
        avatar: newAvatar ?? currentUser.value!.avatar,
        updatedAt: DateTime.now(),
      );

      // 更新数据库
      final result = await _userRepository.updateUser(updatedUser);

      if (result > 0) {
        // 更新用户服务中的当前用户信息
        _userService.currentUser.value = updatedUser;

        // 如果有MeController实例，直接调用其initData方法更新界面
        try {
          if (Get.isRegistered<MeController>()) {
            Get.find<MeController>().initData();
          }
        } catch (e) {
          print('更新Me页面失败: $e');
        }

        // 隐藏加载提示
        EasyLoading.dismiss();

        // 显示成功消息
        EasyLoading.showSuccess('Personal information updated');

        // 延迟返回上一页，以便用户看到成功提示
        Future.delayed(Duration(milliseconds: 1500), () {
          Get.back(); // 返回上一页
        });
      } else {
        throw Exception('Update user information failed');
      }
    } catch (e) {
      // 隐藏加载提示
      EasyLoading.dismiss();

      print('Save user information failed: $e');
      EasyLoading.showError('Update failed, please try again');
    }
  }

  @override
  void onInit() {
    super.onInit();
    nicknameController = TextEditingController();
  }

  @override
  void onReady() {
    super.onReady();
    _initData();
  }

  @override
  void onClose() {
    nicknameController.dispose();
    super.onClose();
  }
}
